1. MySQLdb 的介绍
- 作用: 用于变成原生SQL语句的模块
2. MySQLdb 和 pymysql 的区别
- MySQLdb 和 pymysql 的语法和用法都是一样的,只是所导入的模块名不一样
- MySQLdb 支持 python2
- pymysql 支持 python2、3
3. MySQLdb 的使用
- 添加数据
import MySQLdb
conn = MySQLdb.connect(host='127.0.0.1', user='root', passwd='1234', db='mydb') # 连接数据库
cur = conn.cursor() # 游标: 操作数据
reCount = cur.execute('insert into UserInfo(Name,Address) values(%s,%s)', ('alex', 'usa')) # 执行sql语句
# reCount = cur.execute('insert into UserInfo(Name,Address) values(%(id)s, %(name)s)',{'id':12345,'name':'wupeiqi'}) # 执行sql语句
conn.commit() # 事务: 提交数据到数据库 -> 一定执行 .commit() 方法 将数据提交到数据库,不然会没有效果
cur.close() # 关闭游标
conn.close() # 关闭对数据库的连接
- 删除数据
import MySQLdb
conn = MySQLdb.connect(host='127.0.0.1', user='root', passwd='1234', db='mydb') # 连接数据库
cur = conn.cursor() # 游标: 操作数据
reCount = cur.execute('delete from UserInfo') # 执行sql语句
conn.commit() # 事务: 提交数据到数据库 -> 一定执行 .commit() 方法 将数据提交到数据库,不然会没有效果
cur.close() # 关闭游标
conn.close() # 关闭对数据库的连接
- 修改数据
import MySQLdb
conn = MySQLdb.connect(host='127.0.0.1', user='root', passwd='1234', db='mydb') # 连接数据库
cur = conn.cursor() # 游标: 操作数据
reCount = cur.execute('update UserInfo set Name = %s', ('alin',)) # 执行sql语句
conn.commit() # 事务: 提交数据到数据库 -> 一定执行 .commit() 方法 将数据提交到数据库,不然会没有效果
cur.close() # 关闭游标
conn.close() # 关闭对数据库的连接
- 查询数据
import MySQLdb
conn = MySQLdb.connect(host='127.0.0.1', user='root', passwd='1234', db='mydb') # 连接数据库
cur = conn.cursor() # 游标: 操作数据
reCount = cur.execute('select * from UserInfo') # 执行sql语句
cur.fetchone() # 获取查询到的数据中的一条数据
cur.close() # 关闭游标
conn.close() # 关闭对数据库的连接